﻿using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace libProxy
{
    public class OnRequestFromClientEventArgs : EventArgs
    {
        public string Message { get; set; }
    }

    public class HttpProxy : IProxyServer
    {
        private volatile bool _keepWorking;

        #region IProxyServer Members

        public void Start(IPAddress bind, int port)
        {
            var listener = new TcpListener(bind, port);
            listener.Start();

            var buffer = new byte[512];
            _keepWorking = true;
            while (_keepWorking)
            {
                TcpClient client = listener.AcceptTcpClient();
                Trace.WriteLine("Client connected");
                var sb = new StringBuilder();

                NetworkStream stream = client.GetStream();

                var reader = new StreamReader(stream);
                string ln;
                while (!string.IsNullOrEmpty((ln = reader.ReadLine())))
                {
                    sb.Append(ln);
                }

                string reply;
                if (OnReqestFromClient != null)
                {
                    var args = new OnRequestFromClientEventArgs
                                   {
                                       Message = sb.ToString()
                                   };
                    OnReqestFromClient(this, args);
                    reply = args.Message;
                }
                else
                {
                    reply = "404 Not Found\n";
                }

                var writer = new StreamWriter(stream);
                writer.Write(reply);
                writer.Flush();
                writer.Close();
                client.Close();
            }
        }

        public void Stop()
        {
            _keepWorking = false;
        }

        public event EventHandler<ProxyServerEventArgs> OnClientRequest;

        public void Reply(Socket socket, byte[] bytes)
        {
            throw new NotImplementedException();
        }

        #endregion

        public event EventHandler<OnRequestFromClientEventArgs> OnReqestFromClient;
    }
}